from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import generics
from .models import User
from . import serializers
from rest_framework.permissions import IsAuthenticated

class UsernameCountView(APIView):
    """
    查询用户名是否存在
    select count(*) from 表名 where username=***
    """

    def get(self, request, username):
        # 统计用户名个数
        count = User.objects.filter(username=username).count()
        # 响应
        return Response({
            'username': username,
            'count': count
        })


class MobileCountView(APIView):
    def get(self, request, mobile):
        # 统计手机号个数
        count = User.objects.filter(mobile=mobile).count()
        return Response({
            'mobile': mobile,
            'count': count
        })

class RegisterView(generics.CreateAPIView):
    """
    注册：创建新用户对象
    """
    # 指定查询集：当前只实现创建功能，不需要查询，可以不指定
    # 指定序列化器，验证接收的数据，创建
    serializer_class = serializers.UserRegisterSerializer

class UserView(generics.RetrieveAPIView): # 查询一个的视图类RetrieveAPIView
    # 需要登录
    permission_classes = [IsAuthenticated]

    serializer_class = serializers.UserSerializer
    # 不需要查询，则是获取当前登录的用户
    # queryset = User.objects.all()
    # 重写方法，不跟据主键查询，而是从jwt中获取当前用户
    def get_object(self):
        return self.request.user